/*
 * @descripttion: user controller
 * @author: cp
 * @Date: 2021-04-26 20:58:08
 */

const { getUserInfo, createUser, updateUser } = require('../services/user');
const { SuccessModel, ErrorModel } = require('../model/ResModel');
const { registerUserNameNoExistInfo } = require('../model/ErrorInfo');
const { doCrypto } = require('../utils/cryp');

/**
 * 用户名是否存在
 * @param {string} userName
 */
async function isExist(userName) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    return new SuccessModel(userInfo);
  } else {
    return new ErrorModel({
      message: '用户名未存在',
    });
  }
}

/**
 * 注册接口
 * @param {string} userName 账号
 * @param {string} password 密码
 * @param {string} gender 性别
 */
async function register({ userName, password, gender }) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    return new ErrorModel({
      message: '用户名已存在',
    });
  }

  try {
    await createUser({
      userName,
      password: doCrypto(password),
      gender,
    });
    return new SuccessModel();
  } catch (ex) {
    return new ErrorModel({
      message: '注册失败，请重试',
    });
  }
}

/**
 *
 * @param {Object} ctx koa2 ctx
 * @param {string} userName
 * @param {string} passowrd
 */
async function loginin(ctx, userName, passowrd) {
  // 获取用户信息
  const userInfo = await getUserInfo(userName, doCrypto(passowrd));
  if (!userInfo) {
    return new ErrorModel({
      message: '用户名密码错误',
    });
  }
  if (ctx.session.userInfo == null) {
    ctx.session.userInfo = userInfo;
  }
  return new SuccessModel();
}

/**
 * 修改个人信息
 * @param {Object} ctx
 * @param {string} nickName 昵称
 * @param {string} city 城市
 * @param {string} picture 头像
 */
async function changeInfo(ctx, { nickName, city, picture }) {
  const { userName } = ctx.session.userInfo;
  if (!nickName) {
    nickName = userName;
  }
  const result = await updateUser(
    {
      newNickName: nickName,
      newPicture: picture,
      newCity: city,
    },
    { userName }
  );
  if (result) {
    Object.assign(ctx.session.userInfo, {
      nickName,
      city,
      picture,
    });
    return new SuccessModel();
  }
  return new ErrorModel({
    message: '更新失败',
  });
}

/**
 * 修改密码
 * @param {Object} param0 用户名，新旧密码
 */
async function changePassword({ userName, passowrd, newPassword }) {
  // const
  const result = await updateUser(
    {
      newPassword: doCrypto(passowrd),
    },
    {
      userName,
      passowrd: doCrypto(passowrd),
    }
  );
  if (result) {
    return new SuccessModel();
  }
  return new ErrorModel({
    message: '修改密码失败',
  });
}

module.exports = {
  isExist,
  register,
  loginin,
  changeInfo,
  changePassword,
};
